package com.juyu.miliao.scheduler.service;

import static java.util.Comparator.*;
import static java.util.stream.Collectors.*;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.juyu.miliao.scheduler.dao.mysql.UserInfoDao;
import com.juyu.miliao.scheduler.domin.User;

@Component
public class CommonUserListCacheService {
	private final Logger commonListCacheLogger = LoggerFactory.getLogger("commonListCache");
	@Resource
	private UserInfoDao userInfoDao;
	@Resource
	private StringRedisTemplate stringRedisTemplate;

	/**
	 * 定时更新缓存内容
	 */
	@Scheduled(fixedDelay = 1000 * 60 * 3, initialDelay = 1000 * 25)
	public void executeSchedulerJob() {
		try {
//			CommonSortQuartz common = new CommonSortQuartz();
//			common.call();
			CommonHavingQuartz commonHaving = new CommonHavingQuartz();
			commonHaving.call();
		} catch (Exception e) {
			commonListCacheLogger.error("executeJob error={}", e);
		}
	}

//	private class CommonSortQuartz {
//		private void call() throws Exception {
//			commonListCacheLogger.info("--普通用户--首页壕排行榜排序查询开始：");
//			/** 查询热门 */
//			Set<Integer> collectHot = userInfoDao.getCommonSortUserList().stream()
//					.sorted(comparing(User::getIsVip).thenComparing(comparing(User::getvGradeSum).reversed())).map(User::getUserId)
//					.collect(toCollection(() -> new LinkedHashSet<>()));
//			stringRedisTemplate.delete("commonSort:all");
//			if (!collectHot.isEmpty()){
//				List<String> list = collectHot.stream().map(String::valueOf).collect(toList());
//				if(list.size() > 500)
//					list = list.subList(0, 500);
//				stringRedisTemplate.opsForList().rightPushAll("commonSort:all",list);
//			}
//			/** 清除缓存 */
//			for (int j = 1; j < 51; j++) {
//				stringRedisTemplate.delete("commonCache::" + j);
//			}
//			commonListCacheLogger.info("--普通用户--首页壕排行榜排序查询结束：");
//		}
//	}
	//壕友列表-只显示男性用户-排序优先空闲、繁忙、勿扰、离线，其次各个状态中用户根据等级排序
	private class CommonHavingQuartz {
		private void call() {
			commonListCacheLogger.info("--普通所有用户--首页壕排行榜排序查询开始：");
			//查询在线用户
			List<Integer> uIdList = stringRedisTemplate.opsForZSet().reverseRange("commonSort:onLine",0,-1)
					.stream().map(Integer::parseInt).collect(toList());
			//如果有在线用户，根据在线用户id查询，排序
			List<User> isLineUserList = new ArrayList<>();
			List<Long> returnUserIdList = new ArrayList<>();
			if (uIdList.size()>0){
				isLineUserList = userInfoDao.getUserListByUserIdList(uIdList);
				isLineUserList.forEach(user -> {
					// 判断用户是否勿扰
					if (user.getIsVideo() == 2){
						user.setIsLine(3);
					}else{
						user.setIsLine(1);
					}
				});
				//排序：在线，勿扰-(状态相同是否vip，v等级)
				returnUserIdList = isLineUserList.stream()
						.sorted(comparing(User::getIsLine).thenComparing(User::getIsVip)
								.thenComparing(comparing(User::getvGradeSum).reversed()))
						.map(User::getUserId)
						.collect(toList());
			}
			//如果在线用户不足500，查询非在线用户补充
			int isOnLineSum = returnUserIdList.size();
			List<Long> OffLineUserList = new ArrayList<>();
			if(isOnLineSum < 500){
				OffLineUserList = userInfoDao.getUserListNotByUserIdList(500-isOnLineSum,returnUserIdList)
						.stream().map(User::getUserId).collect(toList());
			}
			returnUserIdList.addAll(OffLineUserList);
			//查询结果存入redis
			if (!returnUserIdList.isEmpty()){
				List<String> list = returnUserIdList.stream().map(String::valueOf).collect(toList());
				if(list.size() > 500)
					list = list.subList(0, 500);
				stringRedisTemplate.delete("commonHaving:all");
				stringRedisTemplate.opsForList().rightPushAll("commonHaving:all",list);
			}
			//清除springCache缓存
			for (int j = 1; j < 51; j++) {
				stringRedisTemplate.delete("commonHavingCache::" + j);
			}
			commonListCacheLogger.info("--普通所有用户--首页壕排行榜排序查询结束：");
		}
	}
}
